package org.servlet;

import org.domain.Account;
import org.domain.Cart;
import org.domain.CartItem;
import org.service.CartService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class UpdateCartServlet extends HttpServlet {
    private static final String VIEW_CART="/WEB-INF/JSP/cart/Cart.jsp";
    private Cart localCart;
    private String itemIdString;
    private CartItem cartItem;
    private int localQuatity;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        localCart = (Cart)session.getAttribute("cart");
        Account account = (Account)session.getAttribute("account");
        for(int i = 0; i < localCart.getCartItemList().size();i++){
            cartItem = localCart.getCartItemList().get(i);
            itemIdString = cartItem.getItem().getItemId();
            localQuatity = Integer.valueOf(request.getParameter(itemIdString));
            cartItem.setQuantity(localQuatity);
        }
        CartService cartService = new CartService();
        cartService.updateCartByUserId(account.getUsername(),localCart);
        System.out.print(account.getUsername());
        session.setAttribute("cart", localCart);
        request.getRequestDispatcher(VIEW_CART).forward(request, response);
    }
}
